package cn.actoncode.boot.framework.common.http.apache;

import cn.actoncode.boot.framework.common.exception.ServiceErrorException;
import cn.actoncode.boot.framework.common.http.RequestHttp;
import cn.actoncode.boot.framework.common.http.RoutinePostRequestExecutor;
import cn.actoncode.boot.framework.common.http.enums.PlatformType;
import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.util.Map;

/**
 * .
 *
 * @author bin
 * @date 2017/5/4
 */
public class ApacheRoutineGetRequestExecutor extends RoutinePostRequestExecutor<CloseableHttpClient, HttpHost> {
    public ApacheRoutineGetRequestExecutor(RequestHttp requestHttp) {
        super(requestHttp);
    }

    @Override
    public ObjectNode execute(String uri, Map<String, String> headers, String queryParam, PlatformType platformType) throws ServiceErrorException, IOException {
        if (queryParam != null) {
            if (uri.indexOf('?') == -1) {
                uri += '?';
            }
            uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
        }
        HttpGet httpGet = new HttpGet(uri);
        if (requestHttp.getRequestHttpProxy() != null) {
            RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
            httpGet.setConfig(config);
        }

        if (CollUtil.isNotEmpty(headers)) {
            for (final Map.Entry<String, String> entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }

        try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet)) {
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            return handleResponse(platformType, responseContent);
        } finally {
            httpGet.releaseConnection();
        }
    }

}
